import { asyncDataFilter, createApp } from "./main";

const { app, router, store } = createApp();

if ((window as any).__INITIAL_STATE__) {
	// store.state.value = JSON.parse((window as any).__INITIAL_STATE__);
	store.replaceState((window as any).__INITIAL_STATE__)
}

router.beforeEach((to, from, next) => {
	// console.log(to)
	next();
})
router.isReady().then(() => {
	router.beforeResolve((to, from, next) => {
		const toComponents = router.resolve(to).matched.flatMap((record: any) =>
			Object.values(record.components)
		)
		const fromComponents = router.resolve(from).matched.flatMap((record: any) =>
			Object.values(record.components)
		)

		const actived = toComponents.filter((c, i) => {
			return fromComponents[i] !== c
		})

		if (!actived.length) {
			return next()
		}
		console.log('开始loading。。。。。')
		asyncDataFilter(actived, store, router.currentRoute).then(() => {
			console.log('结束loading。。。。。')
			next()
		})
	})

	app.mount('#app')
})

router.afterEach((to, from, next) => {
	const { info } = store.state
	const { title: baseTitle = "", keywords:baseKeywords='', description:baseDescription=""  } = info || {}
	const { meta } = to
	const { title, keywords, description } = meta

	const endTitle = baseTitle?baseTitle:title;
	const endKeywords = baseKeywords?baseKeywords:keywords;
	const endDescription = baseDescription?baseDescription:description;
	if (title) {
		document.title = `${endTitle}`
	} else {
		document.title = ""
	}

	const keywordsMeta = document.querySelector('meta[name="keywords"]')
	keywordsMeta && keywordsMeta.setAttribute("content", `${endKeywords}`)

	const descriptionMeta = document.querySelector('meta[name="description"]')
	descriptionMeta?.setAttribute("content", `${endDescription}`)

})